package com.myappengine.controller;

import java.util.logging.Logger;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.myappengine.model.Person;
import com.myappengine.service.PersonService;

@PreAuthorize("hasRole('ROLE_USER')")
@Controller
public class PersonController {
	
	private static Logger logger = Logger.getLogger(PersonController.class.getCanonicalName());
	
	@Autowired
	private PersonService personService;
	
	@ModelAttribute("person")
	public Person createPersonCommand() {
		return new Person("aksjdhf", 10L, "Ha Noi, Viet Nam", 300000.45);
	}
	
	@RequestMapping(value = "/person/create", method = RequestMethod.GET)
	public String createPersonForm() {
		return "createPerson";
	}
	
	@RequestMapping(value = "/person/create", method = RequestMethod.POST)
	public String processPersonSubmit(@ModelAttribute("person") Person person, HttpSession session) {
		Key key = new KeyFactory
				.Builder("Person", "My greate grand father")
				.addChild("Person", "My grand father")
				.addChild("Person", "My father")
				.addChild("Person", "Me")
				.getKey();
		String s = KeyFactory.keyToString(key);
		session.setAttribute("msg", s);
		personService.savePerson(person);
		return "redirect:/persons";
	}
	
	@RequestMapping(value = "/persons", method = RequestMethod.GET)
	public String listPersons(ModelMap model) throws Exception {
		model.addAttribute("persons", personService.getAllPerson());
		return "listPersons";
	}
}
